package com.wl.shop.web;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wl.shop.entity.Menu;
import com.wl.shop.model.DTResult;
import com.wl.shop.model.RestResponse;
import com.wl.shop.utils.StringUtils;
import com.wl.shop.utils.UserUtils;

@Controller
@RequestMapping("${adminPath}/menu")
public class MenuController extends BaseController {
	
	@RequestMapping(value = "list",method = RequestMethod.GET)
	public String list(Model model){
		logger.info("跳转菜单列表---");
		return "sys/menu/list";
	}
	
	@RequestMapping(value = "list",method = RequestMethod.POST)
	@ResponseBody
	public DTResult list(ServletRequest request){
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
		String name = (String)searchParams.get("name");
		DTResult dt = new DTResult();
		EntityWrapper<Menu> wapper = new EntityWrapper<Menu>();
		wapper.eq("is_del", false).orderBy("sort",true);
		if(StringUtils.isNotBlank(name)){
			wapper.like("name", name);
		}else{
			searchParams.remove("name");
		}
		List<Menu> list = menuService.listByParam(wapper);
		dt.setRecordsFiltered(list.size());
		dt.setRecordsTotal(list.size());
		dt.setData(sortTreeList(list));
		return dt;
	}
	
	public List<Menu> sortTreeList(List<Menu> list){
		List<Menu> tree = Lists.newArrayList();
		for (Menu menu : list) {
			if("1".equals(menu.getParentId())){
				tree.add(menu);
				for (Menu child : list) {
					if(child.getParentId().equals(menu.getId())){
						tree.add(child);
						for (Menu cc : list) {
							if(cc.getParentId().equals(child.getId())){
								tree.add(cc);
							}
						}
					}
				}
			}
		}
		return tree;
	}
	
	@RequestMapping(value = "add",method = RequestMethod.GET)
	public String add(Model model){
		model.addAttribute("treeData", UserUtils.getMenuTreeString());
		return "sys/menu/add";
	}
	
	@RequestMapping(value = "add",method = RequestMethod.POST)
	@ResponseBody
	public RestResponse add(@RequestBody Menu menu){
		Menu parent = null;
		if(menu.getName()==null || "".equals(menu.getName())){
			return RestResponse.failure("权限名称不能为空");
		}
		if(menu.getParentId() == null || "".equals(menu.getParentId())){
			return RestResponse.failure("父节点不能为空");
		}else{
			if(!"1".equals(menu.getParentId())){
				parent = menuService.selectById(menu.getParentId());
				if(parent == null){
					return RestResponse.failure("父节点不存在");
				}else{
					menu.setParentIds(parent.getParentIds()+menu.getParentId()+",");
					menu.setParentName(parent.getName());
				}
			}else{
				menu.setParentIds("1,");
				menu.setParentName("根目录");
			}
		}
		int sort = menuService.getMaxSort(menu.getParentId());
		menu.setSort(sort+10);
		menuService.saveOrUpdate(menu);
		return RestResponse.success();
	}
	
	@RequestMapping(value = "edit",method = RequestMethod.GET)
	public String edit(String id,Model model){
		Menu menu = menuService.selectById(id);
		if(menu != null){
			model.addAttribute("menu", menu);
		}
		model.addAttribute("treeData", UserUtils.getMenuTreeString());
		return "sys/menu/edit";
	}
	
	@RequestMapping(value = "edit",method = RequestMethod.POST)
	@ResponseBody
	public RestResponse edit(@RequestBody Menu menu){
		Menu parent = null;
		if(menu.getName()==null || "".equals(menu.getName())){
			return RestResponse.failure("权限名称不能为空");
		}
		if(menu.getParentId() == null || "".equals(menu.getParentId())){
			return RestResponse.failure("父节点不能为空");
		}else{
			if(!"1".equals(menu.getParentId())){
				parent = menuService.selectById(menu.getParentId());
				if(parent == null){
					return RestResponse.failure("父节点不存在");
				}else{
					Menu old = menuService.selectById(menu.getId());
					//如果父目录改变的话 sort值更改，parentIds值更改
					if(!old.getParentId().equals(menu.getParentId())){
						menu.setParentIds(parent.getParentIds()+menu.getParentId()+",");
						int sort = menuService.getMaxSort(menu.getParentId());
						menu.setSort(sort+10);
						menu.setParentName(parent.getName());
					}
				}
			}else{
				menu.setParentIds("1,");
				menu.setParentName("根目录");
			}
		}
		menuService.saveOrUpdate(menu);
		return RestResponse.success();
	}
	
	@RequestMapping(value = "son",method=RequestMethod.GET)
	@ResponseBody
	public RestResponse getSonCategory(@RequestParam(value="id[]",required=false)List<String> id){
		Map<String,Object> map = Maps.newHashMap();
		if(id == null || id.size() == 0){
			return RestResponse.failure("id不能为空");
		}
		for (String i : id) {
			Menu m = menuService.selectById(i);
			EntityWrapper<Menu> wapper = new EntityWrapper<Menu>();
			wapper.eq("is_del", false);
			wapper.like("parent_ids", i);
			List<Menu> list = menuService.listByParam(wapper);
			if(list != null && list.size()>0){
				List<String> names = Lists.newArrayList();
				for (Menu menu : list) {
					names.add(menu.getName());
				}
				map.put(m.getName(), names);
			}
		}
		if(map.isEmpty()){
			return RestResponse.success();
		}else{
			return RestResponse.failure("删除栏目有子栏目").setData(map);
		}
	}
	
	@RequestMapping(value = "delete",method=RequestMethod.POST)
	@ResponseBody
	public RestResponse delete(@RequestParam(value="id[]",required=false)List<String> id){
		if(id == null || id.size() == 0){
			return RestResponse.failure("id不能为空");
		}
		for (String i : id) {
			EntityWrapper<Menu> wapper = new EntityWrapper<Menu>();
			wapper.eq("is_del", false).eq("id", i).or().eq("parent_id", i);
			Menu m = new Menu();
			m.setIsDel(true);
			menuService.updateAll(m, wapper);
		}
		return RestResponse.success();
	}
	
}
